package fun.trackcam.game.balls;

import java.awt.Color;
import java.awt.Graphics;

import sun.nio.cs.HistoricallyNamedCharset;

class Ball {

	/**
	 * State color
	 */
	static Color[] COLOR_STATE = { Color.green, Color.blue, Color.cyan,
			Color.magenta, Color.orange, Color.yellow, };

	/**
	 * Dead state. If a ball is in the dead state, it can't move or be visible.
	 */
	static int DEAD_STATE = -1;

	/**
	 * Initial state
	 */
	static int INIT_STATE = 0;

	/**
	 * the number of collision needeed to change the state of a ball
	 */
	public static final int HIT_COUNT = 5;

	/**
	 * Diameter of the balls
	 */
	public static final int DIAMETER = 50;

	/**
	 * the postition of the ball
	 */
	int width, height;

	/**
	 * the state of the ball
	 */
	int state;

	/**
	 * The actual number of collision. It is reset when the state of the ball
	 * changes
	 */
	int hits;

	// coordinates and value of increment
	double x, y, xinc, yinc, coll_x, coll_y;

	boolean collide;

	/**
	 * the constructor
	 */
	public Ball(int w, int h, int x, int y, double xinc, double yinc) {
		width = w;
		height = h;
		this.x = x;
		this.y = y;
		this.xinc = xinc;
		this.yinc = yinc;
		state = INIT_STATE;
	}

	public double getCenterX() {
		return x + DIAMETER / 2;
	}

	public double getCenterY() {
		return y + DIAMETER / 2;
	}

	/**
	 * Ball behavior
	 */
	public void move() {
		if (state == DEAD_STATE) {
			return;
		}
		if (collide) {
			double xvect = coll_x - getCenterX();
			double yvect = coll_y - getCenterY();

			if ((xinc > 0 && xvect > 0) || (xinc < 0 && xvect < 0))
				xinc = -xinc;

			if ((yinc > 0 && yvect > 0) || (yinc < 0 && yvect < 0))
				yinc = -yinc;

			collide = false;
		}

		x += xinc;
		y += yinc;

		// when the ball bumps against a boundary, it bounces off
		if (x < 0 || x > width - DIAMETER) {
			xinc = -xinc;
			x += xinc;
		}

		if (y < 0 || y > height - DIAMETER) {
			yinc = -yinc;
			y += yinc;
		}
	}

	public void hit(Ball b) {

		if (!collide) {
			coll_x = b.getCenterX();
			coll_y = b.getCenterY();
			collide = true;
			if (state < COLOR_STATE.length - 1) {
				hits--;
				if (hits <= 0) {
					setState(state + 1);
				}
			}
		}
	}

	public void paint(Graphics g) {
		if (state == DEAD_STATE) {
			return;
		}
		g.setColor(COLOR_STATE[state]);
		// the coordinates in fillOval have to be int, so we cast
		// explicitly from double to int
		g.fillOval((int) x, (int) y, DIAMETER, DIAMETER);
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
		hits = HIT_COUNT;
	}

	public double getX() {
		return x;
	}

	public void setX(double x) {
		this.x = x;
	}

	public double getY() {
		return y;
	}

	public void setY(double y) {
		this.y = y;
	}
}
